package com.resurvolution.kingcloudmusicspringboot.product.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.resurvolution.kingcloudmusicspringboot.common.utils.UnifyResult;
import com.resurvolution.kingcloudmusicspringboot.product.dto.ArtistDTO;
import com.resurvolution.kingcloudmusicspringboot.product.entity.ArtistEntity;
import com.resurvolution.kingcloudmusicspringboot.product.mapper.ArtistMapper;
import com.resurvolution.kingcloudmusicspringboot.product.service.ArtistService;
import com.resurvolution.kingcloudmusicspringboot.product.vo.ArtistVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArtistServiceImpl extends ServiceImpl<ArtistMapper, ArtistEntity> implements ArtistService {

    @Resource
    private ArtistMapper artistMapper;

    @Override
    public Integer addArtist(ArtistDTO artistDTO) {
        QueryWrapper<ArtistEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", artistDTO.getName());
        ArtistEntity artistEntity = artistMapper.selectOne(queryWrapper);
        if (artistEntity == null) {
            artistEntity = new ArtistEntity();
            artistEntity.setName((artistDTO.getName()));
            artistEntity.setBio(artistDTO.getBio());
            artistEntity.setCreatedAt(LocalDateTime.now());
            artistMapper.insert(artistEntity);
            return artistEntity.getId();
        } else {
            return artistEntity.getId();
        }
    }

    @Override
    public List<ArtistVO> getArtists(String input) {
        QueryWrapper<ArtistEntity> queryWrapper = new QueryWrapper<>();
        if (input != null) {
            queryWrapper.like("name", input);
            return getArtists(queryWrapper);
        }
        return getArtists(queryWrapper);
    }

    @Override
    public String getArtistById(Integer id) {
        QueryWrapper<ArtistEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("artist_id", id);
        ArtistEntity artistEntity = artistMapper.selectOne(queryWrapper);
        return artistEntity.getName();
    }

    private List<ArtistVO> getArtists(QueryWrapper<ArtistEntity> queryWrapper) {
        return artistMapper.selectList(queryWrapper)
                .stream()
                .map((entity) -> {
                    ArtistVO artistVO = new ArtistVO();
                    artistVO.setName(entity.getName());
                    artistVO.setBio(entity.getBio());
                    artistVO.setId(entity.getId());
                    return artistVO;
                }).collect(Collectors.toList());
    }
}
